# Fork from PSCX, make the Invoke-Elevated command exit immediately after execution.
function InvokeElevatedExit
{
    Write-Debug "`$MyInvocation:`n$($MyInvocation | Out-String)"
 
    $startProcessArgs = @{
        FilePath     = "PowerShell.exe"
        ArgumentList = "-Command", "& {Set-Location '$pwd'}"
        Verb         = "runas"
        PassThru     = $true
        WorkingDir   = $pwd
    }
 
    $OFS = " "
    if ($args.Count -eq 0)      
    {
        Write-Debug "  Starting Powershell without no supplied args"
    }
    elseif ($args[0] -is [Scriptblock]) 
    {
        $script = $args[0]
        if ($script -match '(?si)\s*param\s*\(')
        {
            $startProcessArgs['ArgumentList'] = "-Command", "& {$script}"
        }
        else
        {
            $startProcessArgs['ArgumentList'] = "-Command", "& {Set-Location '$pwd'; $script}"
        }
        [string[]]$cmdArgs = @()
        if ($args.Count -gt 1)
        {
            $cmdArgs = $args[1..$($args.Length-1)]
            $startProcessArgs['ArgumentList'] += $cmdArgs
        }
        Write-Debug "  Starting PowerShell with scriptblock: {$script} and args: $cmdArgs"
    }
    else
    {
        $app = Get-Command $args[0] | Select -First 1 | Where {$_.CommandType -eq 'Application'}
        [string[]]$cmdArgs = @()
        if ($args.Count -gt 1)
        {
            $cmdArgs = $args[1..$($args.Length-1)]
        }
        if ($app) {
            $startProcessArgs['FilePath'] = $app.Path
            if ($cmdArgs.Count -eq 0)
            {
                $startProcessArgs.Remove('ArgumentList')
            }
            else
            {
                $startProcessArgs['ArgumentList'] = $cmdArgs
            }
            Write-Debug "  Starting app $app with args: $cmdArgs"
        }
        else {
            $poshCmd = $args[0]
            $startProcessArgs['ArgumentList'] = "-Command", "& {Set-Location '$pwd'; $poshCmd $cmdArgs}"
            Write-Debug "  Starting PowerShell command $poshCmd with args: $cmdArgs"
        }
    }
 
    Write-Debug "  Invoking Start-Process with args: $($startProcessArgs | Format-List | Out-String)" 
    Microsoft.PowerShell.Management\Start-Process @startProcessArgs
}

Set-Alias sudo InvokeElevatedExit

Export-ModuleMember -Function InvokeElevatedExit
Export-ModuleMember -Alias sudo